/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.result;

import com.jspx.boot.environment.Environment;
import com.jspx.scriptmark.core.script.ScriptTypeConverter;
import com.jspx.sober.config.SoberColumn;
import com.jspx.sober.exception.ValidException;
import com.jspx.sober.util.AnnotationUtil;
import com.jspx.txweb.ActionInvocation;
import com.jspx.txweb.dispatcher.Dispatcher;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.utils.BeanUtil;
import com.jspx.utils.DateUtil;
import com.jspx.utils.StringUtil;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-4-8
 * Time: 上午12:00
 * To change this template use File | Settings | File Templates.
 * Excel 格式返回
 *
 */
public class ExcelResult extends ResultSupport {

    static private String getExcelCaption(Object o) throws ValidException {
        StringBuilder sb = new StringBuilder();
        List<SoberColumn> soberColumn = AnnotationUtil.getColumnList(o.getClass());
        for (SoberColumn column:soberColumn) {
            if (column.isHidden()) continue;
            sb.append(column.getCaption()).append("\t");
        }
        sb.append(StringUtil.CRLF);
        return sb.toString();
    }

    static private String getExcelString(Object o) throws Exception {
        StringBuilder sb = new StringBuilder();
        List<SoberColumn> soberColumn = AnnotationUtil.getColumnList(o.getClass());
        for (SoberColumn column:soberColumn) {
            if (column.isHidden()) continue;
            Object putValue = BeanUtil.getProperty(o, column.getName());
            sb.append(StringUtil.replace(StringUtil.replace(ScriptTypeConverter.toString(putValue),StringUtil.CRLF," "),"\t","              ")).append("\t");
        }
        sb.append(StringUtil.CRLF);
        return sb.toString();
    }

    public void execute(ActionInvocation actionInvocation) throws Exception {
        ActionSupport action = actionInvocation.getActionProxy().getAction();
        action.setActionResult(ActionSupport.NONE);
        HttpServletResponse response = action.getResponse();
        String browserCache = action.getEnv(ActionSupport.BrowserCache);
        if (!StringUtil.isNULL(browserCache) && !StringUtil.toBoolean(browserCache)) {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            response.setDateHeader("Expires", 0);
        }
        Object obj = action.getResult();
        if (obj == null) {

            response.setContentType("text/plain; charset=" + Dispatcher.getEncode());
            PrintWriter write = response.getWriter();
            write.write("无数据");
            write.flush();
            write.close();
            return;
        }

        String name = DateUtil.getDateST();
        //如果头部设置为javascript mootools IE下会自动执行
        response.setHeader("Content-disposition", "attachment;filename=" +  java.net.URLEncoder.encode(name, Environment.defaultEncode)  + ".xls");// 设定输出文件头
        response.setContentType("application/ms-excel");// 定义输出类型
        response.setCharacterEncoding("gb2312");
        PrintWriter write = response.getWriter();
        if (obj instanceof Collection) {
            Collection cols = (Collection) obj;
            int i=0;
            for (Object o : cols) {
                if (i==0)
                    write.write(getExcelCaption(o));
                write.write(getExcelString(o));
                i++;
            }

        } else {
            write.write(getExcelCaption(obj));
            write.write(getExcelString(obj));
        }
        write.flush();
        write.close();
    }
}